import React, { useEffect } from "react";
import type { FormProps } from "antd";
import { Button, Form, Input, InputNumber, Switch } from "antd";
import { data } from "./data";

type FieldType = {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
  collect: boolean;
};

type propsTS = {
  setIsModalOpen: () => void;
  title: string;
  itemobj: Array<FieldType>;
};

const Myform = (props: propsTS) => {
  let { setIsModalOpen, title, itemobj } = props;
  let [form] = Form.useForm();
  useEffect(()=>{
    if(title=="编辑"){
        form.setFieldsValue(itemobj)
    }
  },[title,itemobj])

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    if(title=="新增"){
        let obj={
            ...values,
            tags: ["nice", "developer"],
        }
        data.push(obj)
    }else{
        let obj={
            ...itemobj,
            ...values,
        }
        let idx=data.findIndex(item=>item.key==obj.key)
        data[idx]=obj
    }
    setIsModalOpen(false)
  };

  return (
    <div>
      <Form
        name="basic"
        form={form}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="姓名"
          name="name"
          rules={[{ required: true, message: "请输入你的姓名" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="年龄"
          name="age"
          rules={[{ required: true, message: "请输入你的年龄" }]}
        >
          <InputNumber />
        </Form.Item>

        <Form.Item<FieldType>
          label="详情"
          name="address"
          rules={[{ required: true, message: "请输入详情" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType> label="状态" name="collect">
          <Switch />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Myform;
